from functools import wraps
from flask import request, jsonify
import time
from app.utils.log_control import INFO, ERROR

def error_handler(app):
    @app.errorhandler(Exception)
    def handle_error(error):
        ERROR.logger.error(f"Error: {str(error)}")
        return jsonify({
            "status": "error",
            "message": str(error)
        }), 500

def request_logger():
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            start_time = time.time()
            request_id = request.headers.get('X-Request-ID', '')
            INFO.logger.info(f"Request started: {request.path} [ID: {request_id}]")
            
            try:
                response = f(*args, **kwargs)
                duration = time.time() - start_time
                INFO.logger.info(f"Request completed: {request.path} [ID: {request_id}] ({duration:.2f}s)")
                return response
            except Exception as e:
                duration = time.time() - start_time
                ERROR.logger.error(f"Request failed: {request.path} [ID: {request_id}] ({duration:.2f}s) - {str(e)}")
                raise
        return decorated_function
    return decorator

def init_middleware(app):
    """初始化所有中间件"""
    error_handler(app)
    
    @app.before_request
    @request_logger()
    def before_request():
        pass 